// 引入配置文件
var user_config = require("./config.js");
var upload = require("./upload.js");
var game = require("./game.js");
var utils = require("./utils.js");
var server = require("./server.js");

// ========== API URL 配置 ==========
// 获取API URL配置对象
const apiUrls = user_config.getApiUrls();
// 基础URL
const baseUrl = apiUrls.baseUrl;
// 用户云端配置
const userConfig = apiUrls.configUrl;
// 资源识别API URL
const recognizeUrl = apiUrls.recognizeUrl;
// 上传API URL
const uploadUrl = apiUrls.uploadUrl;
// OCR API URL
const ocrUrl = apiUrls.ocrUrl;
// 配置API URL
const configUrl = apiUrls.configUrl;
// 用户名
const userName = "2362400196";
// 截图路径
const screenshotPath = apiUrls.SCREENSHOT_PATH;
// 剪裁后的图片路径
const croppedPath = apiUrls.CROPPED_PATH;

// ========== 手机型号配置 ==========
const phoneConfig =server.loadConfig(userName,configUrl)

// 全局变量存储最新的资源值
var lastGold = 0;
var lastElixir = 0;

// 持续检测资源数直到达到预设值
function checkResourcesUntilSatisfied() {
    while (true) {
        console.log("等5秒白云")
        sleep(5000);
        console.log("开始检测资源数");
        // 截图 
        
        utils.takeScreenshot(screenshotPath);
        // 裁剪
        utils.cropImage(screenshotPath, phoneConfig.phone_configs.redmin_turbo.resources.x, phoneConfig.phone_configs.redmin_turbo.resources.y, phoneConfig.phone_configs.redmin_turbo.resources.width, phoneConfig.phone_configs.redmin_turbo.resources.height);
        // 上传
        upload.uploadImage(uploadUrl, croppedPath, userName);

        // 获取资源数
        var resources = game.getResources(recognizeUrl, userName);

        
        // 更新全局变量，并转换为整数类型
        lastGold = parseInt(resources.gold, 10);
        lastElixir = parseInt(resources.elixir, 10);
        console.log("预设资源数:", phoneConfig.ziyuan.ziyuan);
        console.log("当前资源: 金币=" + lastGold + ", 圣水=" + lastElixir);

        // 判断资源数是否大于预设值,任意一个条件满足即可
        // 将预设资源数转换为整数类型
        const requiredResource = parseInt(phoneConfig.ziyuan.ziyuan, 10);
        
        
        if (lastGold > requiredResource || lastElixir > requiredResource) {
            console.log("资源数已达到预设值，结束检测");
            // 搜鱼
            //下兵 
            game.sendArmy(phoneConfig.phone_configs.redmin_turbo, phoneConfig.bing);

            break; // 资源满足条件后跳出循环
        } else {
            console.log("资源数未达到预设值，继续检测");
            sleep(3000); // 等待3秒后继续检测
            click(phoneConfig.phone_configs.redmin_turbo.jixu.x, phoneConfig.phone_configs.redmin_turbo.jixu.y);
            
        }
    }
}


// 检测游戏是否结束并回城
function checkGameEndAndReturn() {
    try {
        sleep(3000);
        // 截图
        utils.takeScreenshot(screenshotPath);
        //裁剪
        utils.cropImage(screenshotPath, phoneConfig.phone_configs.redmin_turbo.game_end.x, phoneConfig.phone_configs.redmin_turbo.game_end.y, phoneConfig.phone_configs.redmin_turbo.game_end.width, phoneConfig.phone_configs.redmin_turbo.game_end.height);
        //上传
        upload.uploadImage(uploadUrl, croppedPath, userName);
        
     
        const isGameEnded = game.checkGameEnd(ocrUrl, userName);
    
        
        // 修复布尔值处理问题
        let result;
        if (typeof isGameEnded === 'boolean') {
            result = isGameEnded;
           
        } else if (isGameEnded === "true" || isGameEnded === true || isGameEnded === 1) {
            result = true;
            
        } else {
            result = false;
           
        }
        
        
        return result;
    } catch (error) {
        console.error("checkGameEndAndReturn函数执行出错:", error);
        return false;
    }
}



// 检测游戏是否结束
function continuousGameEndCheck() {
    console.log("开始持续检测游戏是否结束");
    let detectionCount = 0;
    while (true) {
        detectionCount++;   
        // 调用检测函数
        let isGameEnded = false;
        try {
            isGameEnded = checkGameEndAndReturn();
        } catch (error) {
           
            isGameEnded = false;
        }
        
        // 强制转换为布尔值并使用严格相等比较
        // 修复布尔值转换问题
        let isGameEndedBool;
        if (typeof isGameEnded === 'boolean') {
            isGameEndedBool = isGameEnded;
        } else if (isGameEnded === "true" || isGameEnded === true || isGameEnded === 1) {
            isGameEndedBool = true;
        } else {
            isGameEndedBool = false;
        }
        
        
        if (isGameEndedBool === true) {
            console.log("游戏结束，开始回城");
            try {
                click(phoneConfig.phone_configs.redmin_turbo.return_base.x, phoneConfig.phone_configs.redmin_turbo.return_base.y);
                console.log("回城操作执行完毕");
                sleep(1000);
            } catch (error) {
                console.error("执行回城操作时出错:", error);
            }
            break; // 游戏结束时跳出循环
        } else {
            console.log("游戏未结束，5秒后继续检测");
            // 点击夜世界英雄技能
            click(504, 1156);
            if (detectionCount >= 100) { // 限制检测次数，避免无限循环
                console.log("已达到最大检测次数，停止检测");
                break;
            }
            sleep(5000); // 等待5秒后继续检测
        }
    }
}

// 循环执行：搜鱼 -> 检测资源 -> 检测回城
function mainLoop() {
    // 模式判断
    if (phoneConfig.moshi.home == "0") {
        console.log("当前模式为主世界模式");
        var i = 0;
        while (true) {
            i++;
            console.log("第" + i + "次循环开始");
            sleep(1000)
            // 搜鱼
            game.fishing(phoneConfig.phone_configs.redmin_turbo);
            sleep(3000)
            // 调用资源检测函数
            checkResourcesUntilSatisfied();
            
            // 持续检测回城，直到游戏结束
            console.log("开始持续检测游戏是否结束");
            continuousGameEndCheck()
            
            console.log("第" + i + "次循环结束");

        }
    } else {
        console.log("当前模式为夜世界模式");
        var i = 0;
        while (true) {
            i++;
            console.log("第" + i + "次循环开始");
            sleep(1000)
            
            // 点击空白区域，防止弹窗
            click(phoneConfig.phone_configs.redmin_turbo.fishing_start_1.x, phoneConfig.phone_configs.redmin_turbo.fishing_start_1.y);
            sleep(1000);
            click(phoneConfig.phone_configs.redmin_turbo.fishing_start_2.x, phoneConfig.phone_configs.redmin_turbo.fishing_start_2.y);
            sleep(1000);
            click(phoneConfig.phone_configs.redmin_turbo.fishing_start_2.x, phoneConfig.phone_configs.redmin_turbo.fishing_start_2.y);
            sleep(1000);
            click(phoneConfig.phone_configs.redmin_turbo.fishing_start_2.x, phoneConfig.phone_configs.redmin_turbo.fishing_start_2.y);
            // 点击进攻按钮
            click(phoneConfig.phone_configs.redmin_turbo.fishing_start_3.x, phoneConfig.phone_configs.redmin_turbo.fishing_start_3.y);
            sleep(1000);
            // 搜索对手
            click(phoneConfig.phone_configs.redmin_turbo.fishing_start_4.x, phoneConfig.phone_configs.redmin_turbo.fishing_start_4.y);
            sleep(6000);
            game.sendArmyNight(phoneConfig.phone_configs.redmin_turbo, phoneConfig.ybing);
            sleep(1000);
            // 持续检测回城，直到游戏结束
            console.log("开始持续检测游戏是否结束");
            continuousGameEndCheck()


            console.log("第" + i + "次循环结束");

        }
    }
    
}

// 执行主循环
mainLoop();

// //game.sendArmyNight(phoneConfig.phone_configs.redmin_turbo, phoneConfig.ybing);
// console.log(phoneConfig.moshi.home);






